<template>
<div class="h-100 w-100">
    <div class="login h-100 w-100">
        <vue-particles color="#dedede" class="particles"></vue-particles>
        <div class="login-warp">
            <div class="login-header">
                <h1 class="t-c">
                    <p style="font-size:26px;">
                        融合教育云资源平台-学校终端
                    </p>
                    <p style="font-size:20px;">
                        Integrated education cloud resource platform - school terminal
                    </p>
                </h1>
            </div>
            <div class="login-plane" v-loading="loginLoading">
                <el-tabs v-model="activeName" type="card" :before-leave="handleClick" :stretch="true">
                    <el-tab-pane label="老师登录" name="teacherLoginForm">
                        <el-form :model="teacherForm" status-icon :rules="rules" ref="teacherLoginForm" class="form-login">
                            <el-form-item prop="bUserName">
                                <el-autocomplete
                                style="width:340px;"
                                prefix-icon="el-icon-user"
                                v-model.trim="teacherForm.bUserName"
                                :fetch-suggestions="querySearchTeacher"
                                placeholder="请输入机构代码"
                                @select="handleSelect"
                                >
                                    <template slot-scope="{ item }">
                                        <div class="clearfix">
                                            <div class="fl">{{ item.value }}</div>
                                            <i class="fr el-icon-close pointer remove-username" title="点击删除" @click.stop="removeUserNameTeacher(item)"></i>
                                        </div>
                                    </template>
                                </el-autocomplete>
                                <!-- <el-input type="text" v-model="teacherForm.bUserName" placeholder="请输入机构代码" autocomplete="off" prefix-icon="el-icon-s-home"></el-input> -->
                            </el-form-item>
                            <el-form-item prop="bT_Name">
                                <el-input type="text" v-model.trim="teacherForm.bT_Name" placeholder="请输入登陆账户" autocomplete="off" prefix-icon="el-icon-user"></el-input>
                            </el-form-item>
                            <el-form-item prop="bT_PassWord">
                                <el-input type="password" v-model.trim="teacherForm.bT_PassWord" placeholder="请输入登录密码" autocomplete="off" prefix-icon="el-icon-lock"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button style="width:100%;" type="primary" @click="loginTeacher">提交</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="管理员登录" name="userLoginForm">
                        <el-form :model="userForm" status-icon :rules="rules" ref="userLoginForm" class="form-login">
                            <el-form-item prop="username">
                                <el-autocomplete
                                style="width:340px;"
                                prefix-icon="el-icon-user"
                                v-model.trim="userForm.username"
                                :fetch-suggestions="querySearchSys"
                                placeholder="请输入机构代码"
                                @select="handleSelect"
                                >
                                    <template slot-scope="{ item }">
                                        <div class="clearfix">
                                            <div class="fl">{{ item.value }}</div>
                                            <i class="fr el-icon-close pointer remove-username" title="点击删除" @click.stop="removeUserNameSys(item)"></i>
                                        </div>
                                    </template>
                                </el-autocomplete>
                                <el-input style="position:fixed;left:-9999px;"></el-input>
                            </el-form-item>
                            <el-form-item prop="password">
                                <el-input type="password" style="position:fixed;left:-9999px;"></el-input>
                                <el-input type="password" v-model.trim="userForm.password" placeholder="请输入登录密码" autocomplete="off" prefix-icon="el-icon-lock"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button style="width:100%;" type="warning" @click="loginUser">提交</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        <div class="login-footer">
            <h1 class="t-c">
                <p>
                    Copyright © www.ronghejiaoyu.com.cn,All Rights Reserved.
                </p>
                <p>
                    南京融合教育科技有限公司
                </p>
            </h1>
        </div>
    </div>
    <ele-register :bUserName="bUserName" :SECTION="SECTION" :bMSN="bMSN" :isDisabled="isDisabled" :info="registerinfo" :hasValue="hasValue" :bDeptNo="bDeptNo" ref="register"></ele-register>
</div>
    
</template>
<script>
import {login,teacherLogin,getregedit,getSysInfo} from '@/api/index.js'
import eleRegister from './main/register.vue'
export default {
    components:{
        eleRegister
    },
    data() {
        return {
            activeName:'teacherLoginForm',
            teacherForm:{
                bUserName:'',
                bT_Name:'',
                bT_PassWord:''
            },
            userForm:{
                username:'',
                password:'',
                serverip:''
            },
            rules:{
                username:[
                    { required: true, message: '请输入登录账户', trigger: 'change' }
                ],
                password:[
                    { required: true, message: '请输入登录密码', trigger: 'blur' }
                ],
                bT_Name:[
                    { required: true, message: '请输入登录账户', trigger: 'blur' }
                ],
                bUserName:[
                    { required: true, message: '请输入登录账户', trigger: 'change' }
                ],
                bT_PassWord:[
                    { required: true, message: '请输入登录密码', trigger: 'blur' }
                ]
            },
            options:[
                'zahngsan','sasa'
            ],
            SECTION:[],
            loginLoading:false,
            bUserName:'',
            bMSN:'',
            bDeptNo:"",
            registerinfo:{},
            isDisabled:false,
            hasValue:false
        }
    },
    created(){
        this._getSysInfo();
        this.getIP()
    },
    methods:{
        _getSysInfo(){
            getSysInfo({bCode_Parent_NO:'SECTION'}).then((res) => {
                if(res) {
                    this.SECTION = res;
                    localStorage.setItem('SECTION',JSON.stringify(res));
                }
            }).catch(() => {})
        },
        getIP(){
            
            function getUserIP(onNewIP) { //  onNewIp - your listener function for new IPs
                //compatibility for firefox and chrome
                var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
                var pc = new myPeerConnection({
                    iceServers: []
                }),
                noop = function() {},
                localIPs = {},
                ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
                key;
            
                function iterateIP(ip) {
                    if (!localIPs[ip]) onNewIP(ip);
                    localIPs[ip] = true;
                }
            
                //create a bogus data channel
                pc.createDataChannel("");
            
                // create offer and set local description
                pc.createOffer().then(function(sdp) {
                    sdp.sdp.split('\n').forEach(function(line) {
                        if (line.indexOf('candidate') < 0) return;
                        line.match(ipRegex).forEach(iterateIP);
                    });
                    
                    pc.setLocalDescription(sdp, noop, noop);
                }).catch(function(reason) {
                    // An error occurred, so handle the failure to connect
                });
                pc.onicecandidate = function(ice) {
                    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
                    ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
                };
            };
            let that = this;
            getUserIP(function(ip){
                that.userForm.serverip = ip
            });
        },
        handleClick(val){
            this.$refs[val].resetFields();
        },
        handleSelect(item) {
            console.log(item)
            if(this.activeName == 'teacherLoginForm') {
                if(item.adduser) {
                    this.teacherForm.bT_Name = item.adduser;
                } else {
                    this.teacherForm.bT_Name = '';
                }
            }
        },
        loginTeacher() {
            this.$refs.teacherLoginForm.validate((valid) => {
                if (valid) {
                    teacherLogin(this.teacherForm).then((res) => {
                        this.activationStatus(res,'teacher');
                    }).catch((err) => {
                        console.log(err)
                    }).finally(() => {
                        this.loginLoading = false;
                    })
                }
            });
        },
        loginUser() {
            this.$refs.userLoginForm.validate((valid) => {
                if (valid) {
                    this.loginSys(this.userForm)
                }
            });
        },
        getData(queryString, cb,name){
            let localUserInfo = localStorage.getItem(name);
            localUserInfo = localUserInfo ? JSON.parse(localUserInfo) : [];
            var results = queryString ? localUserInfo.filter((item) => item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0) : localUserInfo;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        querySearchTeacher(queryString, cb){
            this.getData(queryString, cb,'userListInfoTeacher')
        },
        querySearchSys(queryString, cb){
            this.getData(queryString, cb,'userListInfoSys')
        },
        removeUserNameSys(row) {
            this.removeItem(row,'userListInfoSys')
        },
        removeUserNameTeacher(row) {
            this.removeItem(row,'userListInfoTeacher')
        },
        removeItem(row,name){
            let localUserInfo = localStorage.getItem(name);
            localUserInfo = localUserInfo ? JSON.parse(localUserInfo) : [];
            let getuser = localUserInfo.filter(item => item.id !== row.id);
            localStorage.setItem(name,JSON.stringify(getuser));
        },
        // 判断用户的激活状态，如果已经激活则直接进入页面
        activationStatus(res,flag){
            if(res.d) {
                let logininfo = JSON.parse(res.d);
                if(logininfo.code == 200) {
                    sessionStorage.setItem('userInfo',JSON.stringify(logininfo.data));
                    // 将登陆的用户信息存储到本地
                    // 先查看本地是否存在登陆的信息，如果存在则添加，否则就新建
                    let loc_name = ""
                    if(flag) {
                        loc_name = "userListInfoTeacher"
                    } else {
                        loc_name = "userListInfoSys"
                    }
                    let localUserInfo = localStorage.getItem(loc_name);
                    localUserInfo = localUserInfo ? JSON.parse(localUserInfo) : [];
                    let hasInfo = localUserInfo.some(item => item.id == logininfo.data.deptid);
                    let obj = {
                            id:logininfo.data.deptid,
                            value:logininfo.data.username,
                            adduser:logininfo.data.adduser
                        };
                    if(!hasInfo) {
                        localUserInfo.push(obj);
                        localStorage.setItem(loc_name,JSON.stringify(localUserInfo));
                    } else {
                        for (let i = 0; i < localUserInfo.length; i++) {
                            const item = localUserInfo[i];
                            if(item.id == logininfo.data.deptid) {
                                localUserInfo[i] = obj;
                                break;
                            }
                        }
                    }
                    this.registerinfo = {};
                    if(logininfo.data.activationstatus == '1') {
                        this.$router.push({path:'/home'})
                    } else if(logininfo.data.activationstatus == '0') {
                        this.bUserName = logininfo.data.username;
                        this.bDeptNo = logininfo.data.deptno;
                        this.bMSN = logininfo.data.MSN;
                        this.isDisabled = false;
                        this.hasValue = false;
                        // 弹出提示框
                        this.$refs.register.dialogVisible = true;
                    } else {
                        getregedit({
                            bDeptID:logininfo.data.deptid,
                            bUserName:logininfo.data.username
                        }).then((res) => {
                            this.isDisabled = true;
                            this.hasValue = true;
                            this.registerinfo = res[0];
                            this.$refs.register.dialogVisible = true;
                        })
                    }
                } else {
                    this.$util.tipsMsg('error',logininfo.message);
                }
            } else {
                this.$util.tipsMsg('error','登陆失败');
            }
        },
        loginSys(params) {
            this.loginLoading = true;
            login(params).then((res) => {
                this.activationStatus(res);
            }).catch((err) => {
                console.log(err)
            }).finally(() => {
                this.loginLoading = false;
            })

        }

    }
}
</script>
<style lang="less">

.login{
    #tab-user.el-tabs__item.is-active{
        color:#E6A23C;
    }
    #userLoginForm:hover{
        color:#E6A23C;
    }
    .el-input__inner{
        padding-left:40px;
    }
}
</style>

<style lang="less" scoped>
.login{
    background-color: rgba(27,148,112);
    position: relative;
    .particles{
        height: 98%;
    }
    .login-header{
        width: 600px;
        h1{
            margin-bottom: 20px;
            color: #fff;
        }
    }
    .login-warp{
        position: absolute;
        left:50%;
        top:40%;
        transform: translate(-50%,-50%);
    }
    .login-plane{
        background-color: #fff;
        width: 420px;
        margin:0 auto;
    }
    .form-login{
        margin:40px;
    }
    .login-footer{
        position: fixed;
        bottom:20px;
        left:50%;
        transform: translateX(-50%);
        h1{
            font-size: 12px;
            color:#fff;
        }

    }
}
</style>
